package bll

import (
	"context"
	"fmt"
	openapi "github.com/alibabacloud-go/darabonba-openapi/v2/client"
	dysmsapi20170525 "github.com/alibabacloud-go/dysmsapi-20170525/v3/client"
	util "github.com/alibabacloud-go/tea-utils/v2/service"
	"github.com/alibabacloud-go/tea/tea"
	log "manager/collector/logger"
	"manager/errors"
	"manager/model"
	"manager/server/web/sms"
	"manager/store/redis"
	"manager/utils"
	"strconv"
)

var Sms = &smsServer{}

type smsServer struct {
}

func (s *smsServer) Send(ctx context.Context, in *model.SmsSendCodeRequest) error {
	var (
		err  error
		code int
	)
	// 4位随机数
	code = utils.GenerateRandomIntCode(6)

	err = s.SendCode(in.Phone, code)
	if err != nil {
		return err
	}
	// 插入到缓存
	err = redis.Sms.SetVerificationCode(ctx, in.Phone, strconv.Itoa(code))
	if err != nil {
		log.Error(err)
		return err
	}
	return nil
}
func (s *smsServer) CheckCode(ctx context.Context, in *model.SmsCheckRequest) error {
	b := redis.Sms.CheckVerificationCode(ctx, in.Phone, strconv.Itoa(in.Code))
	if !b {
		return errors.VerificationCodeError.Error()
	}
	return nil
}

/**
* 使用STS鉴权方式初始化账号Client，推荐此方式。本示例默认使用AK&SK方式。
* @param accessKeyId
* @param accessKeySecret
* @param securityToken
* @return Client
* @throws Exception
 */
func CreateClientWithSTS(accessKeyId *string, accessKeySecret *string, securityToken *string) (_result *dysmsapi20170525.Client, _err error) {
	config := &openapi.Config{
		// 必填，您的 AccessKey ID
		AccessKeyId: accessKeyId,
		// 必填，您的 AccessKey Secret
		AccessKeySecret: accessKeySecret,
		// 必填，您的 Security Token
		SecurityToken: securityToken,
		// 必填，表明使用 STS 方式
		Type: tea.String("sts"),
	}
	// 访问的域名
	config.Endpoint = tea.String("dysmsapi.aliyuncs.com")
	_result = &dysmsapi20170525.Client{}
	_result, _err = dysmsapi20170525.NewClient(config)
	return _result, _err
}

func (s *smsServer) SendCode(phone string, code int) (err error) {
	// 工程代码泄露可能会导致AccessKey泄露，并威胁账号下所有资源的安全性。以下代码示例仅供参考，建议使用更安全的 STS 方式，更多鉴权访问方式请参见：https://help.aliyun.com/document_detail/378661.html
	codeStr := fmt.Sprintf(`{"code":%d}`, code)

	sendSmsRequest := &dysmsapi20170525.SendSmsRequest{
		SignName:      tea.String("电摩智"),
		TemplateCode:  tea.String("SMS_465930519"),
		TemplateParam: tea.String(codeStr),
		PhoneNumbers:  tea.String(phone),
	}

	runtime := &util.RuntimeOptions{}
	resp, err := sms.SmsClient.SendSmsWithOptions(sendSmsRequest, runtime)
	if err != nil {
		log.Error(err)
		return err
	}
	log.Info(util.ToJSONString(resp))
	return err
}
